//
//  ViewModelHelper.swift
//  EVOP
//
//  Created by LC_WJH on 2017/8/15.
//  Copyright © 2017年 gmc. All rights reserved.
//
import Foundation

///基础视图建模辅助类,可以用于Tableview 和 Collectionview 的管理
///它的思想很简单,把管理一个Tableview/Collectionview所需要实现的协议,方法,写进一个基础管理类,使列表能在数据驱动下快速跑起来
///子类在继承了这个管理类后,只需要对需要差异化处理的函数override修改即可,例如  ( cellForRowAt indexPath )
open class BaseViewModel:NSObject,
    UITableViewDelegate,
    UITableViewDataSource,
    UICollectionViewDelegate,
    UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout{
    
    //点击事件
    public typealias  VMTCB = (Any?/*当Any为引用类型时,处理函数不能retain这个传入值,否则内存泄漏*/,Int)->Void
    public typealias  VDDCB = (Any?/*当Any为引用类型时,处理函数不能retain这个传入值,否则内存泄漏*/,Int)->Bool
    var tapcb:VMTCB?;
    var delcb:VDDCB?;
    
    
    public weak var targetTabel:UITableView?;
    public weak var targetCollectionView:UICollectionView?;
    
    
    public var minimumLineSpacingSection:CGFloat = 10;
    public var minimumInteritemSpacingForSection:CGFloat = 10;
    
    
    //辅助启动参数
    open func workWithTalbe(_ table:UITableView,estimateHeight:CGFloat)->Void{
        
        table.delegate = self;
        table.dataSource = self;
        table.estimatedRowHeight = estimateHeight;
        table.rowHeight = UITableView.automaticDimension;
        
        //capture instance
        targetTabel = table;
    }
    
    public var expectItemSize:CGSize!;
    
    open func workWithCollection(_ col:UICollectionView,estimatedSize:CGSize)->Void{
        
        // let fy:UICollectionViewFlowLayout =  UICollectionViewFlowLayout.init();
        expectItemSize = estimatedSize;
        // fy.estimatedItemSize = estimatedSize;
        // fy.scrollDirection = UICollectionViewScrollDirection.horizontal;
        // col.collectionViewLayout = fy;
        col.delegate = self;
        col.dataSource = self;
        //capture instance
        targetCollectionView = col;
    }
    
    public func reloadData(){
        targetTabel?.reloadData();
        targetCollectionView?.reloadData();
    }
    
    ///获取屏幕宽度的均分值
    public static func getWidthByDivScreenWidth(_ div:Int)->CGFloat{
        
        if let kw = UIApplication.shared.keyWindow {
            return kw.bounds.width / CGFloat(div);
        }
        return 0.0;
        
    }
    
    
    ///尝试根据自身内容总高度来自动修改高度约束值,只对AutoLayout中锁定了自身高度约束有效
    public func tryAutoAdjustSelfHeight(){
        
        if targetCollectionView != nil {
            var heightConstance:NSLayoutConstraint?;
            for r in targetCollectionView!.constraints {
                if r.firstItem === targetCollectionView! && r.firstAttribute == NSLayoutConstraint.Attribute.height {
                    heightConstance = r;
                    break;
                }
            }
            
            ///竟然如此狭义
            var heightTimes:Int = 0;
            
            
            let im = CGFloat(ListItems != nil ? ListItems.count : 0);
            var totaWid:CGFloat = expectItemSize.width * im;
            if im > 1 {
                totaWid +=  CGFloat(im - 1) * minimumInteritemSpacingForSection;
            }
            //不考虑padding
            
            let screenWidth =  BaseViewModel.getWidthByDivScreenWidth(1);
            let newLine:Int = totaWid.truncatingRemainder(dividingBy: screenWidth) == 0 ? 0 : 1;
            
            heightTimes = Int(totaWid / screenWidth) + newLine;
            
            
            
            heightConstance?.constant = CGFloat(heightTimes) * expectItemSize.height
            if heightTimes > 1 {
                heightConstance?.constant +=  CGFloat(heightTimes/* - 1*/) * minimumLineSpacingSection;
            }
            return;
        }
        
        if targetTabel != nil {
            
            var heightConstance:NSLayoutConstraint?;
            for r in targetTabel!.constraints {
                if r.firstItem === targetTabel! && r.firstAttribute == NSLayoutConstraint.Attribute.height {
                    heightConstance = r;
                    break;
                }
            }
            
            ///发现约束
            if heightConstance != nil {
                let nh =  targetTabel!.estimatedRowHeight * CGFloat(ListItems != nil ? ListItems.count : 0);
                heightConstance?.constant  =  nh;
            }
        }
    }
    
    
    //点击回调
    open func setCbOnItemTaped(cb:@escaping VMTCB){
        tapcb = cb;
    }
    
    //删除
    open func setCbOnItemDeleted(cb:@escaping VDDCB){
        delcb = cb;
        
    }
    
    //画面表达输出一次,需要具体画面override (这个方法基本没什么用)
    open func expressMyself(toVc:UIViewController){
        
    }
    
    //完整释放自己所占用资源
    open func suiside()->Void{
        
        ListItems?.removeAll();
        ListItems = nil;
        
        targetTabel?.delegate = nil;
        targetTabel?.dataSource = nil;
        
        targetCollectionView?.dataSource = nil;
        targetCollectionView?.dataSource = nil;
        
        tapcb = nil;
        delcb = nil;
    }
    
    
    deinit {
        suiside();
    }
    
    
    //列表数据
    public var ListItems:[Any]! =  [Any]();
    
    
    open func numberOfSections(in tableView: UITableView) -> Int {
        if( ListItems == nil ){
            return 0;
        }
        return 1;
    }
    
    //MARK: tablewview 的 Delegate和DataSource,需要具体画面override
    open func tableView(_ tableView: UITableView, numberOfSections section: Int) -> Int{
        if( ListItems == nil ){
            return 0;
        }
        return ListItems.count > 0 ? 1 : 0;
    }
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if( ListItems == nil ){
            return 0;
        }
        return ListItems.count > 0 ? ListItems.count : 0;
    }
    
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0.01;
    }
    
    //table cell
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let dum:UITableViewCell?=tableView.dequeueReusableCell(withIdentifier: "", for: indexPath);
        return dum!;
    }
    
    /*
     
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
     return 0;
     }
     */
    
    //table selected
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true);
        if indexPath.row < ListItems.count{
            tapcb?( ListItems[indexPath.row],indexPath.row);
        }else{
            tapcb?( nil ,indexPath.row);
        }
    }
    
    open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        //do no thing
    }
    
    open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return false;
    }
    
    open func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除";
    }
    
    
    open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete{
            if indexPath.row < ListItems.count {
                if delcb != nil && delcb!( ListItems[indexPath.row],indexPath.row) {
                    ListItems.remove(at: indexPath.row);
                }
                tableView.reloadData();
            }
        }
    }
    
    
    
    //MARK: UIcollectview 的 Delegate和DataSource,需要具体画面override
    
    
    open func numberOfSections(in collectionView: UICollectionView) -> Int{
        
        collectionView.layoutIfNeeded();
        if( ListItems == nil ){
            return 0;
        }
        return ListItems.count > 0 ? 1 : 0;
        
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        
        return minimumLineSpacingSection;
    }
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return minimumInteritemSpacingForSection;
    }
    
    open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        collectionView.layoutIfNeeded();
        if( ListItems == nil ){
            return 0;
        }
        return ListItems.count > 0 ? ListItems.count : 0;
        
    }
    
    
    
    
    /// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
    open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        
        return collectionView.dequeueReusableCell(withReuseIdentifier: "dummy", for: indexPath);
        
    }
    
    /*
     //大小位置
     open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     return CGSize(width: 0, height: 0)
     }
     //间隔
     open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
     return UIEdgeInsetsMake(0, 0, 0, 0)
     }
     */
    
    //选择
    public var autoClearSelection:Bool = true;
    open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        
        if autoClearSelection {
            collectionView.deselectItem(at: indexPath, animated: true);
        }
        
        if indexPath.row < ListItems.count{
            tapcb?( ListItems[indexPath.row],indexPath.row);
        }else{
            tapcb?( nil,indexPath.row);
        }
        
    }
    
    
}
